package com.alibaba.csp.sentinel.dashboard.rule.apollo.config;

import com.alibaba.csp.sentinel.dashboard.rule.apollo.*;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ApolloConfiguration
 *
 * @author kancy
 * @date 2020/5/4 16:04
 */
@ConditionalOnProperty(value = "sentinel.datasource.mode", havingValue = "apollo")
@Configuration
public class ApolloConfiguration {

    @Bean
    @ConfigurationProperties("sentinel.dashboard.datasource.apollo")
    public ApolloProperties apolloProperties(){
        return new ApolloProperties();
    }

    /**
     * Apollo OpenApi Client
     * @param properties
     * @return
     */
    @Bean
    public ApolloOpenApiClient apolloOpenApiClient(ApolloProperties properties) {
        AssertUtil.notEmpty(properties.getPortalUrl(), "Apollo portalUrl is empty.");
        ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder()
                .withPortalUrl(properties.getPortalUrl())
                .withToken(properties.getToken())
                .withConnectTimeout(properties.getConnectTimeout())
                .withReadTimeout(properties.getReadTimeout())
                .build();
        return client;
    }

    @Bean
    public AuthorityRuleApolloService dynamicAuthorityRuleService(){
        return new AuthorityRuleApolloService();
    }

    @Bean
    public DegradeRuleApolloService dynamicDegradeRuleService(){
        return new DegradeRuleApolloService();
    }

    @Bean
    public FlowRuleApolloService dynamicFlowRuleService(){
        return new FlowRuleApolloService();
    }

    @Bean
    public ParamFlowRuleApolloService dynamicParamFlowRuleService(){
        return new ParamFlowRuleApolloService();
    }

    @Bean
    public SystemRuleApolloService dynamicSystemRuleService(){
        return new SystemRuleApolloService();
    }

    @Bean
    public GatewayFlowRuleApolloService dynamicGatewayFlowRuleService(){
        return new GatewayFlowRuleApolloService();
    }

    @Bean
    public GatewayApiRuleApolloService dynamicGatewayApiRuleService(){
        return new GatewayApiRuleApolloService();
    }
}
